import os
from logging import INFO
from flask import Flask

from handlers import create_BP_handlers

def create_app(debug: bool):
    app = Flask(__name__)
    app.logger.setLevel(INFO)

    bp = create_BP_handlers(debug)
    app.register_blueprint(bp)

    return app

def clear_nohup():
    if os.path.exists('nohup.out'):
        with open('nohup.out', 'w') as f:
            f.write('')

if __name__ == '__main__':
    import asyncio
    import argparse
    from hypercorn.asyncio import serve
    from hypercorn import Config
    from flask_cors import CORS

    parser = argparse.ArgumentParser(description='Run the server')
    parser.add_argument('--debug', '-D', action='store_true', help='Debug mode', default=False)

    args = parser.parse_args()

    clear_nohup()
    config = Config()
    config.bind = ['localhost:38828']
    # config.access_log_format = '%(h)s %(l)s %(l)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
    config.access_log_format = '%(h)s - - "%(R)s" %(s)s length=%(b)s referrer="%(f)s" UA="%(a)s"'
    config.accesslog = '-'
    
    app = create_app(args.debug)
    if args.debug:
        CORS(app)
        app.run(debug=True, host='0.0.0.0', port=38828)
    else:
        asyncio.run(serve(app, config, mode='wsgi'))  
        
